package eteam.aps.controller;

import eteam.aps.common.R;
import eteam.aps.common.component.LoginUserRedisService;
import eteam.aps.common.entity.ParentEntity;
import eteam.aps.common.exceptions.AuthException;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.common.helper.Helper;
import eteam.aps.common.helper.JsonPage;
import eteam.aps.model.entity.Depot;
import eteam.aps.model.vo.DepotVo;
import eteam.aps.service.DepotService;
import eteam.aps.service.QueryInfoService;
import eteam.aps.systeminterface.model.dto.VerifyTokenDto;
import eteam.aps.systeminterface.model.vo.QueryInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仓库控制层
 *
 * @author WMT
 */
@Api(tags = "仓库模块")
@RestController
public class DepotController implements IDepotController{

    @Autowired
    private DepotService depotService;

    @Autowired
    private LoginUserRedisService loginUserRedisService;

    @Autowired
    private QueryInfoService queryInfoService;

    @Override
    @ApiOperation("新增仓库")
    @PostMapping("/de/insert")
    public R<Integer> insert(@RequestBody Depot depot) throws Exception, AuthException {
        VerifyTokenDto user = loginUserRedisService.getUser();
        depot.setfId(Helper.GetId());
        depot.setfState(ParentEntity.FSTATE_DRAFT);
        depot.setfCreateUserId(user.getFuserid());
        depot.setfLastModifyUserId(user.getFuserid());
        LocalDateTime now = LocalDateTime.now();
        depot.setfCreatorTime(now);
        depot.setfLastModifyTime(now);
        depot.setfBookCode(user.getFgrouporgid());

        if (Helper.isEmpty(depot.getfDepotCode()) || Helper.isEmpty(depot.getfDepotName())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库编号或仓库名称不能为空");
        }
        if (Helper.isEmpty(depot.getfManageDepartmentId()) || Helper.isEmpty(depot.getfManageUserId())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库管理部门或管理人员不能为空");
        }
        if (depotService.selectCountByDeCode(depot.getfDepotCode()) > 0){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库编号已存在");
        }
        if (depotService.selectCountByDeName(depot.getfDepotName()) > 0){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库名称已存在");
        }
        return R.success(depotService.insert(depot));
    }

    @Override
    @ApiOperation("删除仓库")
    @PostMapping("/de/delete/{fId}")
    public R<Integer> delete(@PathVariable String fId) throws Exception, AuthException {

        if (Helper.isEmpty(fId)){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库fId不能为空");
        }
        Depot depotDb = depotService.selectByFId(fId);
        if (depotDb == null){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库不存在");
        }
        return R.success(depotService.delete(fId));
    }

    @Override
    @ApiOperation("修改仓库")
    @PostMapping("/de/update")
    public R<Integer> update(@RequestBody Depot depot) throws Exception, AuthException {
        VerifyTokenDto user = loginUserRedisService.getUser();
        depot.setfLastModifyTime(LocalDateTime.now());
        depot.setfLastModifyUserId(user.getFuserid());

        if (Helper.isEmpty(depot.getfDepotCode()) || Helper.isEmpty(depot.getfDepotName())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库编号或仓库名称不能为空");
        }

        Depot depotDb = depotService.selectByFId(depot.getfId());
        if (!depotDb.getfDepotCode().equals(depot.getfDepotCode())){
            if (depotService.selectCountByDeCode(depot.getfDepotCode()) > 0){
                throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库编号已存在");
            }
        }
        if (!depotDb.getfDepotName().equals(depot.getfDepotName())){
            if (depotService.selectCountByDeName(depot.getfDepotName()) > 0){
                throw new BusinessException(HttpStatus.BAD_REQUEST,"仓库名称已存在");
            }
        }
        return R.success(depotService.update(depot));
    }

    @Override
    @ApiOperation("查询仓库列表")
    @PostMapping("/de/selectAll")
    public R<JsonPage<DepotVo>> selectAll(
            @RequestParam(value = "fDepotCode",required = false) String fDepotCode,
            @RequestParam(value = "fDepotName",required = false) String fDepotName,
            @RequestParam("page") Integer page,@RequestParam("pageSize") Integer pageSize
    ) throws Exception, AuthException {
        Map<String,Object> map = new HashMap<>(2);
        if (Helper.isNotEmpty(fDepotCode)){
            map.put("fDepotCode",Helper.likeSql(fDepotCode));
        }
        if (Helper.isNotEmpty(fDepotName)){
            map.put("fDepotName",Helper.likeSql(fDepotName));
        }
        JsonPage<DepotVo> jsonPage = depotService.selectAll(map, Helper.valuePositive(page, 1),Helper.valuePositive(pageSize,10));
        List<DepotVo> list = jsonPage.getList();
        if (list != null){
            for (DepotVo vo : list) {
                vo.setfCreateUserName(queryInfoService.selectUserName().get(vo.getfCreateUserId()));
                vo.setfManageDepartmentName(queryInfoService.selectOrgName().get(vo.getfManageDepartmentId()));
                vo.setfManageUserName(queryInfoService.selectUserName().get(vo.getfManageUserId()));
            }
        }
        return R.success(jsonPage);
    }

    @Override
    @ApiOperation("查询仓库详情")
    @PostMapping("/de/selectDetails/{fId}")
    public R<DepotVo> selectDetails(@PathVariable String fId) throws Exception, AuthException {
        if (Helper.isEmpty(fId)){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"fId不能为空");
        }
        DepotVo depotVo = depotService.selectDetails(fId);
        depotVo.setfCreateUserName(queryInfoService.selectUserName().get(depotVo.getfCreateUserId()));
        depotVo.setfManageDepartmentName(queryInfoService.selectOrgName().get(depotVo.getfManageDepartmentId()));
        depotVo.setfManageUserName(queryInfoService.selectUserName().get(depotVo.getfManageUserId()));
        return R.success(depotVo);
    }

    @ApiOperation("管理部门列表")
    @PostMapping("/de/manageOrgList")
    private R<List<QueryInfoVo>> manageOrgList() throws Exception, AuthException {
        return R.success(queryInfoService.orgList());
    }

    @ApiOperation("管理人员列表")
    @PostMapping("/de/manageUserList/{fOrgId}")
    private R<List<QueryInfoVo>> manageUserList(@PathVariable String fOrgId) throws Exception, AuthException {
        return R.success(queryInfoService.personList(fOrgId));
    }
}
